package com.xidian.zhiancloud.service.dangerWorkTicket;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.SysOrganizationAbandonMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.SysOrganizationAbandon;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.model.dangerWorkTicket.TemplateSource;
import com.xidian.zhiancloud.model.dangerWorkTicket.WorkTicketTemplate;
import com.xidian.zhiancloud.qo.dangerWorkTicket.TemplateQO;
import com.xidian.zhiancloud.service.dangerWorkTicket.WorkTicket.TemplateSourceService;
import com.xidian.zhiancloud.service.dangerWorkTicket.WorkTicket.WorkTicketTemplateService;
import com.xidian.zhiancloud.ticketTemplate.ticketContentRisk.Fire;
import com.xidian.zhiancloud.ticketTemplate.ticketContentRisk.TemplateJson;
import com.xidian.zhiancloud.dao.TemplateMapper;
import com.xidian.zhiancloud.model.Template;
import com.xidian.zhiancloud.vo.dangerWorkTicket.TemplateVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class TemplateService extends ServiceImpl<TemplateMapper, Template> implements IService<Template> {
    @Autowired
    private TemplateMapper templateMapper;

    @Autowired
    private SysOrganizationAbandonMapper sysOrganizationAbandonMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TemplateSourceService templateSourceService;

    @Autowired
    private WorkTicketTemplateService workTicketTemplateService;

    @Autowired
    private ReviewWorkBeforeService reviewWorkBeforeService;

    public Map<Byte, Integer> statisticsByOrganizationId(Long id, Long companyId, Date stratTime, Date endTime) {
        Map<Byte, Integer> ans = new HashMap<>();
        List<Template> list = null;
        if (id == null) {
            LambdaQueryWrapper<Template> query = Wrappers.<Template>lambdaQuery();
            query.eq(Template::getCompanyId, companyId).between(Template::getCreateTime,stratTime,endTime);
            list = templateMapper.selectList(query);
        } else {
            Queue<Long> queue = new LinkedList<>();
            List<Long> ids = new LinkedList<>();
            ids.add(id);
            queue.add(id);
            while (!queue.isEmpty()){
                Long front = queue.poll();
                LambdaQueryWrapper<SysOrganizationAbandon> query = Wrappers.<SysOrganizationAbandon>lambdaQuery();
                query.eq(SysOrganizationAbandon::getPid, front);
                List<SysOrganizationAbandon> tmp = sysOrganizationAbandonMapper.selectList(query);
                for (SysOrganizationAbandon sysOrganizationAbandon : tmp){
                    ids.add(sysOrganizationAbandon.getId());
                    queue.add(sysOrganizationAbandon.getId());
                }
            }

            LambdaQueryWrapper<Template> query = Wrappers.<Template>lambdaQuery();
            query.in(Template::getId, ids);
            list = templateMapper.selectList(query);
        }
        if(list == null){
            return ans;
        } else {
            for (Template template : list){
                if (!ans.containsKey(template.getTicketType())){
                    ans.put(template.getTicketType(), 1);
                }else {
                    ans.put(template.getTicketType(), ans.get(template.getTicketType()) + 1);
                }
            }
        }
        return ans;
    }

    /**
     * 作用：统计一定时间段内，各种作业票类型的数量
     * 返回值类型：map，参数一为作业票类型，参数二为对应作业票的数量
     * 函数逻辑：票类型 = ticket.type，Byte的Integer对象 + 1
     */
    public Map<Byte, Integer> statisticsByType(long companyId, Date stratTime, Date endTime) {
        Map<Byte, Integer> ans = new HashMap<>();
        List<Template> list = null;
        LambdaQueryWrapper<Template> query = Wrappers.<Template>lambdaQuery();
        query.eq(Template::getCompanyId, companyId).between(Template::getCreateTime,stratTime,endTime);
        list = templateMapper.selectList(query);
        for (Template i : list){
            // 缺少判断时间是否成立
            if(ans.containsKey(i.getTicketType())){
                ans.put(i.getTicketType(), ans.get(i.getTicketType()) + 1);
            }
        }
        return ans;
    }

    public void add(Template template) {
        // 先填充Json文件的内容
        template.setContent(TemplateJson.test());
        templateMapper.insert(template);
        // 再将共有内容和JSON内容一同传入template中
        this.save(template);
    }

    public void test(){

        Template t1 = new Template();
        t1.setContent(TemplateJson.test());
        templateMapper.insert(t1);
    }

    public TemplateVO getVOById(Long id) {
        Template template = templateMapper.selectById(id);
        if (template == null){
            throw new CustomizeException(GeneralResponseEnums.GET_FAILED);
        }
        TemplateVO vo = new TemplateVO();
        BeanUtils.copyProperties(template, vo);

        // 用户
        SysUser creator = sysUserMapper.selectById(vo.getCreatorId());
        vo.setCreatorName(creator == null ? "该用户不存在" : creator.getName());

        // 作业区域/地点
        SysOrganizationAbandon org = sysOrganizationAbandonMapper.selectById(vo.getOrganizationId());
        vo.setLocationName(org == null ? "该部门已被删除" : org.getName());

        return vo;
    }

    public IPage<TemplateVO> getListByQO(TemplateQO templateQO){                // 分页
        Page<TemplateVO> page = new Page<>(templateQO.getCurrent(), templateQO.getSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("start_time").setAsc(false);
        page.getOrders().add(orderItem);
        return templateMapper.getListByQO(page,templateQO);
    }


    public Boolean initFire() {
        TemplateSource fireSource = new TemplateSource();
        // mysql不能存List<String>类型，还是需要String类型
        // List<String> 转为 String

        fireSource.setContent(Fire.fireRiskStr());
        fireSource.setName("动火");
        fireSource.setType(1);
        Boolean res = templateSourceService.save(fireSource);
        return res;
    }

    public Boolean initCompany(Long companyId) {
        WorkTicketTemplate fireSource = new WorkTicketTemplate();
        fireSource.setContent(Fire.fireRiskStr());
        fireSource.setName("动火作业票");
        fireSource.setCompanyId(companyId);
        fireSource.setType(1);
        Boolean res = workTicketTemplateService.save(fireSource);
        return res;
    }


    public List<String> returnRiskList(WorkTicketTemplate workTicketTemplate) {
        String risk_s = workTicketTemplate.getContent();                                                   // 风险辨识
        List<String> risks = new LinkedList<>();
        for(String risk : risk_s.split("。")) {
            risks.add(risk);
        }
        return risks;
    }

}
